package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.FileUploadVo;
import com.ybkj.daijia.common.MediaUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.Advertisement;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.service.AdvertisementService;
import com.ybkj.daijia.server.service.CompanyService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * 广告位信息请求控制器
 *
 * @author zane
 */
@Controller
@RequestMapping("advertisement")
public class AdvertisementController {

    @Autowired
    private AdvertisementService advertisementService;
    @Autowired
    private CompanyService companyService;

    /**
     * 获取广告位列表
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
//		Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView();
        mv.addObject("companys", companyService.findAll());
        mv.setViewName("setting/advertisementList");
        return mv;
    }

    @RequestMapping(value = "createAdvertisement", method = RequestMethod.POST)
    public @ResponseBody
    Result<Object> createAdvertisement(@RequestParam("linkAddress") String linkAddress,
        @RequestParam("sequence") Integer sequence,
        @RequestParam(required = false, value = "picture") String picture,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "companyName") String companyName)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("weixin")) {
            if (!principal.isCompanyType()) {
                companyId = principal.getCompanyId();
            }

            Company company = companyService.findOne(companyId);
            if (!company.isCompanyType()) {
                List<Advertisement> total = advertisementService.findByCompanyId(companyId);
                if (total != null && total.size() >= 3) {
                    return new Result<Object>(false, "分公司最多只能上传3张图片哟，亲");
                }
            }
            if (principal.isCompanyType()) {
                advertisementService
                    .createAdvertisement(companyId, companyName, linkAddress, sequence, picture);
            } else {
                advertisementService
                    .createAdvertisement(principal.getCompanyId(), principal.getCompanyName(),
                        linkAddress, sequence, picture);
            }

            return new Result<Object>(true, "创建成功");
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updateAdvertisement", method = RequestMethod.POST)
    public @ResponseBody
    Result<Object> updateAdvertisement(
        @RequestParam(required = false, value = "linkAddress") String linkAddress,
        @RequestParam("id") Long id,
        @RequestParam(required = false, value = "sequence") Integer sequence,
        @RequestParam(required = false, value = "picture") String picture,
        @RequestParam(required = false, value = "companyId") Long companyId) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("weixin")) {
            Advertisement advertisement = advertisementService.findById(id);
            if (StringUtils.isNotBlank(linkAddress)) {
                advertisement.setLinkAddress(linkAddress);
            }
            if (StringUtils.isNotBlank(picture)) {
                advertisement.setPicture(picture);
            }
            if (sequence != null) {
                advertisement.setSequence(sequence);
            }
            if (principal.isCompanyType()) {
                advertisement = advertisementService.updateAdvertisement(advertisement);
            } else {
                advertisement = advertisementService.updateAdvertisement(advertisement);
            }

            return new Result<Object>(true, "修改成功");
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "advertisementData", method = RequestMethod.GET)
    public @ResponseBody
    Page<Advertisement> advertisementData(
        @RequestParam(required = false, value = "companyName") String companyName)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("weixin")) {
            Page<Advertisement> page = null;
            if (principal.isCompanyType()) {
                page = advertisementService.advertisementData(companyName);
            } else {
                page = advertisementService.advertisementData(principal.getCompanyAbbreviation());
            }
            return page;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "deleteById", method = RequestMethod.GET)
    public @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("weixin")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                Advertisement advertisement = advertisementService.findById(id);
                if (null != advertisement) {
                    advertisementService.delete(advertisement);
                    String bathPath = getBasePath(req);
                    String picture = advertisement.getPicture();
                    if (StringUtils.isNotBlank(picture)) {
                        File f = new File(bathPath, advertisement.getPicture());
                        if (f.exists()) {
                            f.delete();
                        }
                    }

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadImg")
    public @ResponseBody
    FileUploadVo uploadImg(@RequestParam("picture_file") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/advertisement/" + monthstr + "/" + now.getTime()
                + moduleName.substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); // 上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(540, 260).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

}
